import Cfg from './config.js'

const chkUpgrade=(appInfo)=>{	
	console.log('APP更新入口正常！')	
	let appVersion = appInfo.version.replace(/[.]/g, "") 
	let appName = appInfo.name
	let phoneOS = uni.getSystemInfoSync().platform;
	let ckUrl = Cfg.cfg.update_api;		
	uni.request({
		url: ckUrl,	
		method: 'POST',
		dataType:"json",
		header:{'content-type':'application/x-www-form-urlencoded'},
		data:{...appInfo,system:phoneOS},			
		success: res => {		
			console.log('获取远程版本资料正常！')
			let androidUdateFile = res.data.android //安卓更新文件
			let iosUdateFile = res.data.ios //ios更新文件	
			let updateFile = phoneOS == "android" ? androidUdateFile : iosUdateFile	
			let locVer = parseInt(appVersion);//本地版本
			let remVer = parseInt(updateFile.lastVersion.replace(/[.]/g, ""));//远程版本		
				console.log('本地版本：'+locVer,'线上版本：'+remVer)
			if (remVer > locVer) {	
				console.log('线上版本大于本地版本需要进行升级')
				if (updateFile.updateType) {
					console.log('进行整包更新中...')
					packageDownload(updateFile) //整包更新
				} else {
					console.log('进行热更新中...')
					wgtDownload(updateFile) //wgt更新
				}
			}
			console.log('不需要更新！')
		},
		fail: (e) => {
			
		},
	});
}

//热更新
const wgtDownload = (fileInfo)=>{
	console.log('开始下载热更新文件...')
	let dtask = plus.downloader.createDownload(
		fileInfo.wgtDownUrl, {
			filename: '_doc/update/' + new Date().getTime() + '/'
		},
		(res, code) => {
			console.log('下载热更新文件完成！')
			plus.runtime.install(
				res.filename, {
					force: false
				},
				(res) => {
					uni.hideLoading();					
					plus.runtime.restart();
					
				},
				(e) => {
					//console.log(e)
					uni.hideLoading();
				}
			);
		}
	);	
	try {
		/* 监听下载进度 */
		dtask.start(); // 开启下载的任务
		var prg = 0;
		var showLoading = plus.nativeUI.showWaiting("正在更新"); //创建一个showWaiting对象 
		dtask.addEventListener('statechanged', function(
			task,
			status
		) {
			// 给下载任务设置一个监听 并根据状态  做操作
			switch (task.state) {
				case 1:
					showLoading.setTitle("正在更新");
					break;
				case 2:
					showLoading.setTitle("已连接到服务器");
					break;
				case 3:
					prg = parseInt(
						(parseFloat(task.downloadedSize) /
							parseFloat(task.totalSize)) *
						100
					);
					showLoading.setTitle("  正在更新" + prg + "%  ");
					break;
				case 4:
					plus.nativeUI.closeWaiting();
					//下载完成
					break;
			}
		});
	} catch (err) {
		plus.nativeUI.closeWaiting();
		uni.showToast({
			title: '更新失败',
			mask: false,
			duration: 1500
		});
	}	
		
}

//下载APK
const apkDownload = (fileInfo,cb) => {
	console.log('开始下载安卓安装包...')
	let dtask = plus.downloader.createDownload(
		fileInfo.appDownUrl, {
			filename: '_doc/update/' + new Date().getTime() + '/'
		},
		(res, code) => {
			console.log('下载安卓安装包完成！')
			uni.hideLoading();			
			plus.runtime.install(
				res.filename, {
					force: false
				},
				(res) => {
					/* 重新启动APP资源 */
					plus.runtime.restart()
				},
				(e) => {
					console.log(e);
					/* 更新失败做的操作 */
				}
			);			
			cb && cb(true)			
		}
	);	
	try {
		/* 监听下载进度 */
		dtask.start(); // 开启下载的任务
		var prg = 0;
		var showLoading = plus.nativeUI.showWaiting("正在下载"); //创建一个showWaiting对象 
		dtask.addEventListener('statechanged', function(
			task,
			status
		) {
			// 给下载任务设置一个监听 并根据状态  做操作
			switch (task.state) {
				case 1:
					showLoading.setTitle("正在下载");
					break;
				case 2:
					showLoading.setTitle("已连接到服务器");
					break;
				case 3:
					prg = parseInt(
						(parseFloat(task.downloadedSize) /
							parseFloat(task.totalSize)) *
						100
					);
					showLoading.setTitle("  正在下载" + prg + "%  ");
					break;
				case 4:
					plus.nativeUI.closeWaiting();
					//下载完成
					break;
			}
		});
	} catch (err) {
		plus.nativeUI.closeWaiting();
		uni.showToast({
			title: '更新失败',
			mask: false,
			duration: 1500
		});
		cb && cb(false)	
	}	
}

//整包更新
const packageDownload = (fileInfo)=>{
	let title = `检测到有最新版本${fileInfo.appVersion}，是否确认更新?`
	if(fileInfo.appDownTip) title  = fileInfo.appDownTip;	
	if(fileInfo.appIsMarket){//直接是市场的更新			
		uni.showModal({
			title: "提示",
			showCancel:fileInfo.updateForce ? false :true,
			content: title,
			success: function(res) {				
				if (res.confirm) {					
					if(fileInfo.updateForce){
						plus.runtime.openURL(encodeURI(fileInfo.appDownUrl)) //整包下载					
						if(fileInfo.platform == 'ios'){
							plus.ios.import("UIApplication").sharedApplication().performSelector("exit")
						}else{
							plus.runtime.quit();
						}					
					}else{
						plus.runtime.openURL(encodeURI(fileInfo.appDownUrl)) //整包下载
					}
				}else{
					if(fileInfo.updateForce){
						plus.runtime.openURL(encodeURI(fileInfo.appDownUrl)) //整包下载					
						if(fileInfo.platform == 'ios'){
							plus.ios.import("UIApplication").sharedApplication().performSelector("exit")
						}else{
							plus.runtime.quit();
						}					
					}else{
						plus.runtime.openURL(encodeURI(fileInfo.appDownUrl)) //整包下载
					}
				}
			}
		});		
	}else{
		if(fileInfo.platform == 'ios'){//IOS必须重新下载安装
			uni.showModal({
				title: "提示",
				content: title,
				showCancel:false,
				success: function(res) {
					if (res.confirm) {
						plus.runtime.openURL(encodeURI(fileInfo.appDownUrl)); //整包下载
						plus.ios.import("UIApplication").sharedApplication().performSelector("exit")
					}else{
						uni.showToast({
							icon:"none",
							title:'版本太低，请先更新！',
							duration:1500,
							complete:()=>{									
							}
						});
						setTimeout(()=>{							
							plus.ios.import("UIApplication").sharedApplication().performSelector("exit")
						},1500)	
					}
				}
			});
		}else{
			uni.showModal({
				title: "提示",
				content: title,
				showCancel:false,
				success: function(res) {
					if (res.confirm) {
						apkDownload(fileInfo,(e)=>{
							plus.runtime.quit();
						})
					}else{
						uni.showToast({
							icon:"none",
							title:'版本太低，请先更新！',
							duration:1500,
							complete:()=>{									
							}
						});
						setTimeout(()=>{							
							plus.runtime.quit();
						},1500)	
					}
				}
			});	
		}
	}	
}

module.exports = {    
	upgrade:chkUpgrade
}